package com.ruoyi.system.outto.game.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.core.OutUrlConstant;
import com.ruoyi.system.outto.core.RegionalCovert;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.ITQYIAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/21 13:30
 */
@Slf4j
@Service
public class TQYYAPIImpl implements ITQYIAPI {

    @Resource
    private InfoImgMapper infoImgMapper;
    @Autowired
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;
    private SalePartner salePartner;

    public static void main(String[] args) {
//        String APPID =  "9964";
//        String TOKEN = "c629a1a0a891379024ac1a4e971baec1";
//
//        Map<String,Object> params = new HashMap<>();
//        params.put("appId",APPID);
//        params.put("token",TOKEN);
//        params.put("title","1211312");
//        params.put("introduce","11123");
//        params.put("content","1123");
//        params.put("bprice","1213");
//        params.put("price","1231");
//        params.put("gameId","205");
//        params.put("areaId","213");
//        params.put("roles","213");
//        params.put("isBface","0");
//        params.put("isBtel","0");
//        params.put("isMail","0");
//        params.put("productType","1");
//        params.put("grade","10");
//        params.put("pic1","https://game.ikbh.top/logo/no_img.jpg");
//        params.put("param1","20");
//        params.put("param2","20");
//        params.put("isIndemnity","1");
//        params.put("isRecovery","1");
//        params.put("changeGameRealName","2");
//
//
//        String cover = MapUntils.getCover(params);
//        cover = cover.substring(0,cover.length()-1);
//        String baseUrl = "http://b.taoqiyou.com";
////        String path = "/api/open/v1/product/get-area?parentid=2";
//        String path = "/api/open/v1/product/add-product?"+cover;
//        String response = HttpUtils.sendPost(baseUrl + path, null, "application/x-www-form-urlencoded");
//        System.out.println(response);
        long time = DateUtils.getNowDate().getTime();
        System.out.println(time);

        /**
         * 获取游戏ID
         *
         */
    }


    private Map<String,Object> params(AccountInfo accountInfo,SalePartner sa){



        Map<String,Object> params = new HashMap<>();
        params.put("appId",this.salePartner.getSaleKey());
        params.put("token",this.salePartner.getOther());
        params.put("grade","10");
        params.put("otherNo",accountInfo.getId());

        String title = accountInfo.getDes();
        if (accountInfo.getDes().length() > 150){
            title = accountInfo.getDes().substring(0,150);
        }
        //标题
        params.put("title","【xyr_"+accountInfo.getId() + "】"+ accountInfo.getLevel() + "  "  + title);
        params.put("introduce","【xyr_"+accountInfo.getId() + "】"+ accountInfo.getDes());

        BigDecimal bigDecimal = commonApi.addPrice(accountInfo.getPrice(), sa.getSeleep());
        commonApi.setPrice(bigDecimal,accountInfo.getId(),sa);

        params.put("bprice",bigDecimal.stripTrailingZeros().toPlainString());
        params.put("price",bigDecimal.stripTrailingZeros().toPlainString());
        String type = RegionalCovert.typeToTQY(accountInfo.getType());
        if (StringUtils.isNull(type)){
            return AjaxResult.error("游戏类型未找到");
        }
        if ("207".equals(type)){
            if (null == accountInfo.getSuit()){
                params.put("param1",0);
            }else {
                params.put("param1",accountInfo.getSuit());
            }
            if (null == accountInfo.getGuns()){
                params.put("param2",0);
            }else {
                params.put("param2",accountInfo.getGuns());
            }

        }else {
            if (null == accountInfo.getHeroes()){
                params.put("param1",0);
            }else {
                params.put("param1",accountInfo.getHeroes());
            }
            if (null == accountInfo.getSkins()){
                params.put("param2",0);
            }else {
                params.put("param2",accountInfo.getSkins());
            }
        }
        params.put("gameId",type);
        String regional = RegionalCovert.toTQY(accountInfo.getRegional());
        if (StringUtils.isNull(regional)){
            return AjaxResult.error("大区未找到");
        }
        params.put("areaId",regional);
        params.put("isBface","0");
        params.put("isBtel","0");
        params.put("isMail","0");
        params.put("productType","1");

        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        if (CollectionUtils.isEmpty(infoImgs)){
            params.put("pic1",this.salePartner.getTwoOther());
        }else {
            if (infoImgs.size() > 5){
                for (int i=1;i <=5; i++){
                    params.put("pic"+i,infoImgs.get(i-1).getImgUrl());
                }
            }else {
                for (int i=1;i <=infoImgs.size(); i++){
                    params.put("pic"+1,infoImgs.get(i-1).getImgUrl());
                }
            }

        }
        StringBuffer imgs = new StringBuffer();
        if (!CollectionUtils.isEmpty(infoImgs)){
            for (InfoImg img : infoImgs) {
                String imgStr = img.getImgUrl()+" ";
                imgs.append("<img src="+imgStr+"/>");
            }
        }
        String content = "<h3>" + accountInfo.getDes() + "</h3>";
        params.put("content",content+imgs.toString());

        params.put("isIndemnity","1");
        params.put("isRecovery","1");
        params.put("changeGameRealName","0");

        return params;

    }


    @Override
    public AjaxResult addGame(AccountInfo accountInfo,Long userId,SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = params(accountInfo,salePartner);
        String path = "/api/open/v1/product/add-product";
        String paramsStr = JSONObject.toJSONString(params);
        log.info("淘气游新增请求参数={}",paramsStr);
        String response = HttpUtils.doPostForm(OutUrlConstant.TQYURL + path,params,null);
        log.info("淘气游新增返回参数={}",response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String msg = resultJson.getString("msg");
        msg = MapUntils.unicodeToString(msg);
        if (!"0".equals(resultJson.getString("code"))){
//            return AjaxResult.error(msg);
            throw new GlobalException(msg);
        }

        Map<String, Object> result = new HashMap<>();
        if (!"0".equals(resultJson.getString("code"))){
            result.put("code",500);
        }else {
            result.put("code",200);
        }

        result.put("req",JSONObject.toJSONString(params));
        result.put("res",response);
        result.put("msg",msg);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(AccountInfo accountInfo, Long userId, SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = params(accountInfo,salePartner);
        String path = "/api/open/v1/product/update-product";
        String paramsStr = JSONObject.toJSONString(params);
        log.info("淘气游编辑请求参数={}",paramsStr);
        String response = HttpUtils.doPostForm(OutUrlConstant.TQYURL + path,params,null);
        log.info("淘气游编辑返回参数={}",response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String msg = resultJson.getString("msg");
        msg = MapUntils.unicodeToString(msg);
        Map<String, Object> result = new HashMap<>();
        if (!"0".equals(resultJson.getString("code"))){
            result.put("code",500);
        }else {
            result.put("code",200);
        }
        result.put("req",JSONObject.toJSONString(params));
        result.put("res",response);
        result.put("msg",msg);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult delGame(Long id,Long userId,SalePartner sa) {
        Map<String,Object> params = new HashMap<>();
        params.put("appId",sa.getSaleKey());
        params.put("token",sa.getOther());
        params.put("otherNo",id);
        String paramsStr = JSONObject.toJSONString(params);
        log.info("淘气游删除请求参数={}",paramsStr);
        String path = "/api/open/v1/product/product-lower";
        String response = HttpUtils.doPostForm(OutUrlConstant.TQYURL + path,params,null);
        Map<String, Object> result = new HashMap<>();
        if (StringUtils.isNotEmpty(response)){
            log.info("淘气游删除返回参数={}",response);
            JSONObject resultJson = JSONObject.parseObject(response);
            String msg = resultJson.getString("msg");
            msg = MapUntils.unicodeToString(msg);
            if (!"0".equals(resultJson.getString("code"))){
                result.put("code",500);
            }else {
                result.put("code",200);
            }
            result.put("req",JSONObject.toJSONString(params));
            result.put("res",response);
            result.put("msg",msg);
        }else {
            result.put("code",500);
            result.put("req",JSONObject.toJSONString(params));
            result.put("res","操作失败");
            result.put("msg","操作失败");
        }
        return AjaxResult.success(result);
    }
}
